package com.lean.android.ad.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.webkit.CookieManager
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import com.lean.android.ad.core.R
import com.lean.android.ad.utils.StatusBarHelper

class SimpleWebViewActivity: Activity() {
    
    companion object{
        
        private const val ExtraUrl = "url"
        
        fun launch(context: Context, url: String){
            val intent = Intent(context, SimpleWebViewActivity::class.java)
            intent.putExtra(ExtraUrl, url)
            context.startActivity(intent)
        }
    }
    
    private lateinit var backButton: ImageView
    
    private lateinit var webView: WebView
    
    private lateinit var titleView: TextView
    
    private lateinit var iconClose: ImageView
    
    private var url: String? = null
    

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        com.lean.android.ad.utils.StatusBarHelper.translucent(this)
        com.lean.android.ad.utils.StatusBarHelper.setStatusBarLightMode(this)

        setContentView(R.layout.layout_webview_ad)
        
        url = intent.getStringExtra(ExtraUrl)
        
        backButton = findViewById(R.id.iv_sgad_back)
        webView = findViewById(R.id.fixedWebView)
        titleView = findViewById(R.id.tv_sgad_title)
        iconClose = findViewById(R.id.iv_web_close)
        
        initView()
        initWebSetting()

        url?.also {
            webView.loadUrl(it)
        }
    }
    
    private fun initView(){
        iconClose.setOnClickListener { 
            finish()
        }
        
        backButton.setOnClickListener { 
            if(webView.canGoBack()){
                webView.goBack()
            }else{
                finish()
            }
        }
        
    }
    
    private fun initWebSetting(){
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webView.settings.safeBrowsingEnabled = false
        }

        //支持获取手势焦点
        webView.requestFocusFromTouch()
        val webSettings: WebSettings = webView.settings
        //设置开启javascript支持
        webSettings.javaScriptEnabled = true
        //设置支持缩放
        webSettings.setSupportZoom(true)
        //开启缩放工具（会出现放大缩小的按钮）
        webSettings.builtInZoomControls = false
        //WebView两种缓存（网页、H5）方式，此处网页不缓存
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        //允许JS打开新窗口（默认false）
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        //打开本地缓存供JS调用
        webSettings.domStorageEnabled = true
        //webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        //H5缓存路径
        val absolutePath = applicationContext.cacheDir.absolutePath
        //是否允许WebView访问内部文件（默认true）
        webSettings.allowFileAccess = true
        //启动概述模式浏览界面，当页面宽度超过WebView显示宽度时，缩小页面适应WebView(默认false)
        webSettings.loadWithOverviewMode = true

        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (url.startsWith("weixin://wap/pay?")) {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.data = Uri.parse(url)
                    startActivity(intent)
                    return true
                }
                return true
            }

            override fun shouldOverrideUrlLoading(
                view: WebView,
                request: WebResourceRequest
            ): Boolean {
                val url = request.url.toString()
                if (url.startsWith("weixin://wap/pay?")) {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.data = Uri.parse(url)
                    startActivity(intent)
                    return true
                }
                return true
            }

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                handler?.proceed()  // 接受所有网站的证书

            }
        }
        webView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                setTitle(title)
            }

            override fun onProgressChanged(view: WebView, progress: Int) {
                super.onProgressChanged(view, progress)
            }
        }
    }

    private fun setTitle(title: String) {
        if (!TextUtils.isEmpty(title) && !title.startsWith("http") && !title.startsWith("www.")) {
            titleView.text = title
        } else {
            titleView.text = ""
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        webView.clearCache(true)
        webView.clearHistory()
        webView.removeAllViews()
    }

}